import random

from django.http import HttpResponse, JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from celery_tasks.sms.tasks import celery_send_sms_code
from utils.captcha.captcha import captcha
from utils.sms.sms_util import send_sms


class ImageCodeView(View):

    def get(self, requests, uuid):
        # 生成验证码
        text, img = captcha.generate_captcha()
        # 保存数据库
        redis_cli = get_redis_connection("code")
        # 返回数据
        redis_cli.setex(uuid, 120, text)
        print("图片验证码:", text)
        return HttpResponse(img, content_type='image/jpeg')


class SmsCodeView(View):

    def get(self, requests, mobile):
        # redis连接
        redis_cli = get_redis_connection("code")

        # 判断是否频繁发送
        sms_flg = redis_cli.get("sms_rtime_%s" % mobile)

        if not sms_flg is None:
            return JsonResponse({"code": 400, "message": "不要频繁发送 。。。。。 are you ok？？"})

        img_code = requests.GET.get("image_code")
        uuid = requests.GET.get("image_code_id")

        if not all([uuid, img_code]):
            return JsonResponse({"code": 400, "message": "what ? sm wanyer"})

        # 获取数据库中的验证码

        redis_code = redis_cli.get(uuid)

        if not redis_code:
            return JsonResponse({"code": 400, 'message': "重新输入图片验证码"})
        if str(img_code).lower() != redis_code.decode().lower():
            return JsonResponse({"code": 400, "message": "重新 输入"})

        # 删除uuid
        try:
            redis_cli.delete(uuid)
        except Exception as e:
            print(e)

        # 生成短信验证码内容
        sms_num = random.randint(0, 999999)
        sms_str = "%06d" % sms_num
        # 保存到redis
        print("短信验证码:", sms_str)

        # 创建redis管道
        pl = redis_cli.pipeline()

        pl.setex("sms_%s" % mobile, 300, sms_str)
        # 设置间隔时间
        pl.setex("sms_rtime_%s" % mobile, 60, "1")
        # 执行请求
        pl.execute()

        # 发送短信验证吗
        send_sms.send_message(mobile, (sms_str, "5"))

        # celery_send_sms_code.delay(mobile, sms_str)

        print("发送成功")
        return JsonResponse({"code": 0, "message": "发送成功"})
